package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sql.TasksForUserStoryDao;
import beans.TaskBean;

/**
 * Servlet implementation class AddTaskToUserStory
 */
@WebServlet("/AddTaskToUserStory")
public class AddTaskToUserStory extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddTaskToUserStory() {
        super();
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		TaskBean taskData = new TaskBean();
		taskData.setName(request.getParameter("task-name"));
		taskData.setDescription(request.getParameter("task-description"));
		try {
			taskData.setUserStoryId(Integer.parseInt(request.getParameter("user-story-id")));
			String estimateString = request.getParameter("estimate");
			if (estimateString.isEmpty()) {
				taskData.setEstimate(0.0F);
			}
			else {
				taskData.setEstimate(Float.parseFloat(estimateString));
			}
			taskData.setStatusId(Integer.parseInt(request.getParameter("task-status")));
			taskData.setAssignedToId(Integer.parseInt(request.getParameter("assigned-to")));
		}
		catch (NumberFormatException e) { 
			e.printStackTrace();
		}
			
		TasksForUserStoryDao tasksForUserStoryDao = new TasksForUserStoryDao();
		try {
			tasksForUserStoryDao.insert(taskData);
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}
		
		// return data
		PrintWriter out = response.getWriter();
		out.write(taskData.getJson());

	}

}
